package com.gitee.theskyzero.distribution.netty.chat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.GlobalEventExecutor;

public class ChatServer {

    public static void main(String[] args) throws InterruptedException {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(
                new NioEventLoopGroup(1),
                new NioEventLoopGroup(1)
        ).option(ChannelOption.SO_BACKLOG, 1024)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(new ChatServerHandle());
                    }
                });

        ChannelFuture sync = serverBootstrap.bind(8082).sync();
        System.out.println("群聊服务器启动成功");
        sync.channel().closeFuture().sync();
    }


    static class ChatServerHandle extends SimpleChannelInboundHandler<String> {

        public static final ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            Channel channel = ctx.channel();
            System.out.println(String.format("[群聊][%s]上线", channel.remoteAddress()));
            channelGroup.writeAndFlush(String.format("小伙伴[%s] 上线啦", channel.remoteAddress()));
            channelGroup.add(channel);
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            Channel channel = ctx.channel();
            System.out.println(String.format("[群聊][%s]发言:%s", channel.remoteAddress(), msg));
            channelGroup.forEach(
                    ch -> ch.writeAndFlush(String.format("[%s]:%s", ch.equals(channel) ? "me" : channel.remoteAddress(), msg))
            );
        }
    }


}
